package Server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import Client.Client_Gui;

public class Chat_Server_Return implements Runnable{

	Socket sock;
	private Scanner input;
	private PrintWriter out;
	String message = "";
	
	public Chat_Server_Return(Socket soc){
		this.sock=soc;
	}
	
	public void CheckConnection(Socket s)throws IOException{
		if(!s.isConnected()){
			
			System.out.println(Client_Gui.userName);
			for(int i=1;i <=Chat_Server.connectionArray.size(); i++){
				if(Chat_Server.connectionArray.get(i) == s){
					Chat_Server.connectionArray.remove(i);
				}
			}
			for(int i=1;i <=Chat_Server.connectionArray.size(); i++){
				Socket temp_sock = (Socket) Chat_Server.connectionArray.get(i-1);
				PrintWriter temp_out = new PrintWriter(temp_sock.getOutputStream());
				temp_out.println(temp_sock.getLocalAddress().getHostName()+" disconnected");
				temp_out.flush();
				System.out.println(temp_sock.getLocalAddress().getHostName()+ " disconnected");
				temp_sock.close();
		}
	}
}
	

	@Override
	public void run() {
		try {
			try{
			input = new Scanner(sock.getInputStream());
			out = new PrintWriter(sock.getOutputStream());
			
			while(true){
				CheckConnection(sock);
				if(!input.hasNext()){
					return;
				}
				message = input.nextLine();
				System.out.println("Client said: "+ message);
				//Client_Gui.chatArea.append(message+"\n");
				for(int i=1; i<=Chat_Server.connectionArray.size();i++){
					Socket temp_sock = (Socket) Chat_Server.connectionArray.get(i-1);
					CheckConnection(temp_sock);
					PrintWriter temp_out = new PrintWriter(temp_sock.getOutputStream());
					temp_out.println(message);
					temp_out.flush();
					System.out.println("Sent to: "+temp_sock.getLocalAddress().getHostName());
				}
			}
			
			}finally{
				//sock.close();
			}
		} catch (IOException e) {
			System.out.println(e);
			e.printStackTrace();
		}
	}
}